//
//  ChooseView.swift
//  SinaBlog
//
//  Created by 有何不可 on 16/1/10.
//  Copyright © 2016年 有何不可. All rights reserved.
//

import UIKit
import SVProgressHUD
let itemW = (kScreenWidth - 4 * margin) / 3
let ChooseViewReuseIdentifier = "ChooseViewReuseIdentifier"

class ChooseView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, ChooseViewCellDelegate {
    
    private lazy var images: [UIImage] = [UIImage]()
    
    var callBack: (() -> ())?
    
    func addimages(image: UIImage) {
        
        images.append(image)
        
        reloadData()
        
        if images.count == 9 {
            
            SVProgressHUD.showErrorWithStatus("只能一次发布9张图片")
            
            UIView.animateWithDuration(3, animations: { () -> Void in
                SVProgressHUD.dismiss()
            })
        }
    }
    
    init() {
        
        super.init(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        setUI()
        
        backgroundColor = UIColor.grayColor()
    }
    
    private func setUI() {
        
        registerClass(ChooseViewCell.self, forCellWithReuseIdentifier: ChooseViewReuseIdentifier)
        
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.minimumInteritemSpacing = margin
        flowLayout.minimumLineSpacing = margin
        flowLayout.itemSize = CGSizeMake(itemW, itemW)
        
        dataSource = self
        delegate = self
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK: --数据源方法

extension ChooseView {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9{
            
            return images.count
        } else {
            return images.count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(ChooseViewReuseIdentifier, forIndexPath: indexPath) as! ChooseViewCell
        
        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.yellowColor() : UIColor.greenColor()
        
        //本来indexPath.item本身是比images.count要小1个,当相等时候 就是给数组中多添加了一个加号图片
        if indexPath.item == images.count {
            
            cell.image = nil
            
        }else {
            
            cell.image = images[indexPath.item]
        }
        
        cell.delegate = self
        
        cell.indexPath = indexPath
        
        return cell
    }
    
  
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
      
        if indexPath.item == images.count {
            
            callBack?()
        }
        
    }
    // MARK: --ChooseViewCellDelegate实现其代理方法
    func didDelete(indexPath: NSIndexPath) {
        
        print(indexPath.item)
        images.removeAtIndex(indexPath.item)
        reloadData()
    }
}




protocol ChooseViewCellDelegate: NSObjectProtocol {
    
    func didDelete(indexPath: NSIndexPath)
}


//MARK: --自定义Cell
class ChooseViewCell: UICollectionViewCell {
    
    var indexPath: NSIndexPath?
    
    weak var delegate: ChooseViewCellDelegate?
    
    var image: UIImage? {
        
        didSet {
            
            if image == nil {
                
                imageView.image = UIImage(named: "compose_pic_add_highlighted")
                deleteBtn.hidden = true
                
            }else {
                
                imageView.image = image
                
                deleteBtn.hidden = false
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setUI() {
        
        addSubview(imageView)
        addSubview(deleteBtn)
        
        imageView.frame = bounds
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(self.snp_top)
            make.right.equalTo(self.snp_right)
        }
    }
    
   @objc private func deleteEliment() {
        print("delete")
    
    delegate?.didDelete(indexPath!)
    }
    
    private lazy var imageView = UIImageView()
    
    private lazy var deleteBtn: UIButton = {
        
        let btn = UIButton(type: .Custom)
        
        btn.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        
        btn.addTarget(self, action: "deleteEliment", forControlEvents: .TouchUpInside)
        
        btn.sizeToFit()
        
        return btn
        }()
}